package c.x.jy.threadquery;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@SuppressWarnings("all")
public class OrderService {

	OrderServiceImpl orderServiceImpl = new OrderServiceImpl();
	static BlockingQueue<Request> queue = new LinkedBlockingQueue();
	ScheduledExecutorService e = Executors.newScheduledThreadPool(1); // 开启线程
	public void init() {
 
		
		e.scheduleAtFixedRate(new Runnable() {
			@Override
			public void run() {
				int size = queue.size();
		
				if (size == 0)
					return;
				List<Request> requests = new ArrayList<>();
				for (int i = 0; i < size; i++) {
					Request request = queue.poll();
					requests.add(request);
				}
		 
			 
				// 根据Requests封装成批量参数
				List<Map<String, String>> params = new ArrayList<>();
				for (Request request : requests) {
					Map<String, String> map = new HashMap();
					map.put("orderCode", request.orderCode);
					map.put("serialNo", request.serialNo);
					params.add(map);
				}

				List<Map<String, Object>> reslist = orderServiceImpl.querylist(params);

				HashMap<String, Map<String, Object>> responseMap = new HashMap<>();
				// 根据SERIALNO 找到响应结果
				for (Map<String, Object> response : reslist) {
					try {
						String seriaNo = response.get("serialNo").toString();
						responseMap.put(seriaNo, response);
					} catch (Exception e2) {
						e2.printStackTrace();
					}
					
				}
				for (Request req : requests) {
						req.future.complete(responseMap.get(req.getSerialNo()));
					//	System.out.println(responseMap.get("serialNo"));
				}
				 

			}

		}, 0, 12, TimeUnit.MILLISECONDS);

	}

	public Map<String, Object> querybyID(String code) throws InterruptedException, ExecutionException   {
		Request req=new Request();
		req.serialNo=UUID.randomUUID().toString();
		req.setOrderCode(code);
		CompletableFuture<Map<String, Object>> future=	new CompletableFuture<>();
		req.setFuture(future);
		queue.put(req);
		//System.out.println("add: "+code);
		return   future.get();
	}
	
	public void close(){
		
		 e.shutdown();
	}

}
